<template>
  <div class="collection-data-management">
    <!-- 页面头部 -->
    <CollectionHeader 
      :stats="stats"
      :loading="loading"
      :capturing="capturing"
      :selected-records="selectedRecords"
      :view-mode="viewMode"
      :show-advanced-filter="showAdvancedFilter"
      @search="handleSearch"
      @reset="handleReset"
      @toggle-filter="showAdvancedFilter = !showAdvancedFilter"
      @view-mode-change="viewMode = $event"
      @showImportWizard="showImportDialog = true"
      @smart-filter="showFilterDialog = true"
      @show-batch-operations="showBatchDialog = true"
      @load-records="loadCollectionRecords"
      @export-records="handleExportRecords"
      @handle-smart-capture="handleSmartCapture"
    />
    
    <!-- 高级筛选 -->
    <CollectionFilterData 
      v-show="showAdvancedFilter"
      v-model="queryParams"
      @search="handleSearch"
      @reset="handleReset"
    />
    
    <!-- 智能建议 -->
    <SmartActions 
      v-if="showSmartActions"
      :smart-suggestions="smartSuggestions"
      :get-suggestion-type="getSuggestionType"
      @apply-suggestion="applySuggestion"
      @apply-all-suggestions="applyAllSuggestions"
      @remove-suggestion="removeSuggestion"
    />
    
    <!-- 智能提醒 -->
    <CollectionSmartAlerts 
      :records="tableData"
      @alert-click="handleAlertClick"
    />
    
    <!-- 催款记录表格 -->
    <CollectionTableData
      ref="collectionTableRef"
      v-model:query-params="queryParams"
      :table-data="tableData"
      :loading="loading"
      :pagination="{ page: queryParams.page, limit: queryParams.limit, total: total }"
      :selected-records="selectedRecords"
      :show-advanced-filter="showAdvancedFilter"
      @selection-change="handleSelectionChange"
      @view-detail="handleViewRecordDetail"
      @edit="handleEditRecordRemark"
      @refresh="loadCollectionRecords"
    />
    
    <!-- 分页 -->
    <CollectionPagination
      :model-value="{ page: queryParams.page, limit: queryParams.limit }"
      :total="total"
      @update:model-value="(val: { page: number; limit: number }) => { queryParams.page = val.page; queryParams.limit = val.limit }"
      @size-change="handlePageSizeChange"
      @current-change="handlePageChange"
    />
    
    <!-- 导入向导对话框 -->
    <CollectionImportWizardData 
      v-model="showImportDialog" 
      @import-success="handleImportSuccess"
    />
    
    <!-- 智能过滤设置抽屉 -->
    <SmartFilter 
      v-model="showFilterDialog" 
      @rules-updated="handleFilterRulesUpdated"
    />
    
    <!-- 批量操作面板 -->
    <BatchOperationPanel 
      v-model="showBatchDialog" 
      :selected-records="selectedRecords"
      @batch-action="handleBatchAction"
    />
    
    <!-- 催款记录详情对话框 -->
    <CollectionDetail
      v-model="showRecordDetailDialog"
      :record="currentRecord"
      @edit="handleEditRecordRemark"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import CollectionHeader from './components/CollectionHeader.vue'
import CollectionFilterData from './components/CollectionFilter.vue'
import CollectionTableData from './components/CollectionTable.vue'
import CollectionDetail from './components/CollectionDetail.vue'
import CollectionImportWizardData from './components/CollectionImportWizard.vue'
import CollectionPagination from './components/CollectionPagination.vue'
import CollectionSmartAlerts from './components/CollectionSmartAlerts.vue'
import SmartActions from './components/SmartActions.vue'
import SmartFilter from './components/SmartFilter.vue'
import BatchOperationPanel from './components/BatchOperationPanel.vue'

interface CollectionQueryParams {
  customerName: string
  collectionMethod: string
  collectionResult: string
  dateRange: string[]
  page: number
  limit: number
}

// 数据管理模式相关数据
const capturing = ref(false)
const showAdvancedFilter = ref(false)
const smartSuggestions = ref<any[]>([])
const filterRules = ref<any[]>([])
const currentRecordId = ref('')
const currentRecord = ref<any>(null)
const showRecordDetailDialog = ref(false)
const showImportDialog = ref(false)
const showFilterDialog = ref(false)
const showBatchDialog = ref(false)
const tableData = ref<any[]>([])
const total = ref(0)

// 计算属性
const showSmartActions = computed(() => smartSuggestions.value.length > 0)

// 响应式数据
const loading = ref(false)
const selectedRecords = ref<any[]>([])

// 查询参数
const queryParams = reactive<CollectionQueryParams>({
  customerName: '',
  collectionMethod: '',
  collectionResult: '',
  dateRange: [],
  page: 1,
  limit: 20
})

// 视图模式
const viewMode = ref('data')

// 方法
const loadCollectionRecords = async () => {
  loading.value = true
  try {
    // 模拟API调用
    setTimeout(() => {
      tableData.value = [
        {
          id: '1',
          orderInfo: {
            platformOrderId: 'PO2023001',
            amount: 15000.00,
            orderDate: '2023-01-15'
          },
          customerInfo: {
            name: '测试客户A',
            contactPerson: '张三',
            phone: '13800138000',
            email: 'zhangsan@test.com'
          },
          collectionInfo: {
            collectionId: 'COL000001',
            method: 'phone',
            duration: 15,
            result: '已联系客户，承诺3月底付款',
            collectionTime: '2023-03-01',
            operator: '李四',
            notes: '客户资金紧张，需分期付款',
            isBatch: false,
            nextFollowupDate: '2023-03-15',
            satisfactionScore: 4
          }
        }
      ]
      total.value = 1
      loading.value = false
    }, 500)
  } catch (error) {
    ElMessage.error('加载催款记录失败')
    loading.value = false
  }
}

const handleSearch = () => {
  queryParams.page = 1
  loadCollectionRecords()
}

const handleReset = () => {
  Object.assign(queryParams, {
    customerName: '',
    collectionMethod: '',
    collectionResult: '',
    dateRange: []
  })
  queryParams.page = 1
  loadCollectionRecords()
}

const handleSelectionChange = (selection: any[]) => {
  selectedRecords.value = selection
}

const handleViewRecordDetail = (record: any) => {
  currentRecord.value = record
  showRecordDetailDialog.value = true
}

const handleEditRecordRemark = (record: any) => {
  // 编辑备注的逻辑
  ElMessage.success('备注已更新')
}

const handleExportRecords = () => {
  // 处理导出
  ElMessage.info('导出功能开发中')
}

const handleImportSuccess = () => {
  loadCollectionRecords()
  ElMessage.success('导入成功')
}

const handlePageChange = (page: number) => {
  queryParams.page = page
  loadCollectionRecords()
}

const handlePageSizeChange = (size: number) => {
  queryParams.limit = size
  queryParams.page = 1
  loadCollectionRecords()
}

const handleSmartCapture = () => {
  capturing.value = true
  // 智能抓取的逻辑
  setTimeout(() => {
    capturing.value = false
    ElMessage.success('智能抓取完成')
    // 重新加载数据
    loadCollectionRecords()
  }, 2000)
}

// 智能建议相关方法
const loadSmartSuggestions = async () => {
  // 模拟加载智能建议
  smartSuggestions.value = [
    {
      id: '1',
      type: 'followup',
      description: '建议跟进3条即将到期的催款记录',
      records: ['1', '2', '3'],
      confidence: 92
    }
  ]
}

const getSuggestionType = (type: string) => {
  const typeMap: Record<string, string> = {
    followup: 'warning',
    priority: 'success',
    duplicate: 'info'
  }
  return typeMap[type] || 'info'
}

const applySuggestion = (suggestion: any) => {
  // 应用建议的逻辑
  ElMessage.success('建议已应用')
  // 重新加载数据
  loadCollectionRecords()
}

const applyAllSuggestions = () => {
  // 应用所有建议的逻辑
  ElMessage.success('所有建议已应用')
  // 重新加载数据
  loadCollectionRecords()
}

const removeSuggestion = (suggestionId: string) => {
  smartSuggestions.value = smartSuggestions.value.filter((s: any) => s.id !== suggestionId)
}

const handleFilterRulesUpdated = (rules: any[]) => {
  filterRules.value = rules
  ElMessage.success('过滤规则已更新')
  // 重新加载数据
  loadCollectionRecords()
}

const handleBatchAction = (action: string, data: any) => {
  ElMessage.success(`批量操作"${action}"执行成功`)
  // 重新加载数据
  loadCollectionRecords()
}

const handleAlertClick = (alert: any) => {
  ElMessage.info(`处理提醒: ${alert.title}`)
}

// 生命周期
onMounted(() => {
  loadCollectionRecords()
  loadSmartSuggestions()
})
</script>

<style scoped lang="scss">
.collection-data-management {
  padding: 20px;
}

@media (max-width: 768px) {
  .collection-data-management {
    padding: 12px;
  }
}
</style>